package com.xu.seckillkill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xu.seckillkill.dao.GetPakge;
import com.xu.seckillkill.dao.RedPacketInfoMapper;
import com.xu.seckillkill.dao.RedPacketRecordMapper;
import com.xu.seckillkill.pojo.GetPacketReq;
import com.xu.seckillkill.pojo.RedPacketInfo;
import com.xu.seckillkill.pojo.RedPacketRecord;
import com.xu.seckillkill.service.PackageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;

/**
 * @version v1.0
 * @类描述：
 * @项目名称：
 * @包名： com.xu.seckillkill.service.impl
 * @类名称：PackageServiceImpl
 * @创建人：YIHANG.XU
 * @创建时间：2021/2/1411:21 下午
 * @修改人：YIHANG.XU
 * @修改时间：2021/2/1411:21 下午
 * @修改备注：
 * @Copyright
 */
@Service
public class PackageServiceImpl implements PackageService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedPacketInfoMapper packetInfoMapper;
    @Autowired
    private RedPacketRecordMapper redPacketRecordMapper;
    @Autowired
    private GetPakge getPakge;
    private static final String TOTAL_NUM = "_totalNum";
    private static final String TOTAL_AMOUNT = "_totalAmount";

    @Override
    public void addRedEnvelope(RedPacketInfo redPacketInfo) {
        long redPacketId = System.currentTimeMillis();
        //数据插入db
        packetInfoMapper.insert(redPacketInfo);
        redisTemplate.opsForValue().set(redPacketId + TOTAL_NUM, redPacketInfo.getTotalAmount() + "");
        redisTemplate.opsForValue().set(redPacketId + TOTAL_NUM, redPacketInfo.getTotalPacket() + "");

    }

    @Override
    public RedPacketInfo getRedPackage(GetPacketReq req) {
        Integer randomAmount = 0;
        String redPacketName = req.getRedPacketId() + TOTAL_NUM;
        //红包总金额
        String totalAmountName = req.getRedPacketId() + TOTAL_AMOUNT;
        if (redisTemplate.hasKey(redPacketName)) {
            Integer num = Integer.valueOf(redisTemplate.opsForValue().get("redPacketName") + "");
            if (num != null && num > 0) {
                //红包数量减一
                redisTemplate.opsForValue().decrement(redPacketName);
            }

        }
       /* if (redisService.exists(redPacketName)) {
            Integer num = Integer.valueOf(redisService.get(redPacketName) + "");
            if (num != null && num > 0) {
                //红包数减一
                redisService.decr(redPacketName);

                //拿到红包总金额
                if (redisService.exists(totalAmountName)){
                    Integer totalAmount=Integer.valueOf(redisService.get(totalAmountName)+"");
                    //红包最大金额
                    Integer maxMoney=totalAmount/Integer.valueOf(num)*2;
                    Random random=new Random();
                    //随机抢到的红包
                    randomAmount =num==1?totalAmount:random.nextInt(maxMoney);
                    //redis红包金额减指定值
                    redisService.decr(totalAmountName,randomAmount);
                }
                updateRedPacketInDB(req.getUid(),req.getRedPacketId(),randomAmount);
                return JsonData.buildSuccess("抢到红包:"+randomAmount);
            } else {
                return JsonData.buildError("红包被抢完啦");
            }
        } else {
            return JsonData.buildError("红包不存在，请重试");
        }*/
        return null;
    }

    /**
     * 更新用户抢到红包记录
     *
     * @param uid         用户id
     * @param redPacketId 红包id
     * @param amount      金额
     */
    private void updateRedPacketInDB(int uid, Long redPacketId, int amount) {
        RedPacketRecord redPacketRecord = new RedPacketRecord();
        redPacketRecord.setUid(uid);
        redPacketRecord.setNickName("陈彦斌");
        redPacketRecord.setImgUrl("https://images.cnblogs.com/cnblogs_com/chenyanbin/1560326/o_qianxun.jpg");
        redPacketRecord.setRedPacketId(redPacketId);
        redPacketRecord.setAmount(amount);
        redPacketRecord.setCreateTime(new Date());
        redPacketRecordMapper.insert(redPacketRecord);
        //这里还需要更新发红包的数据，红包总个数-1；总金额减去已抢红包数，这里不实现了，自行实现功能
    }
    public void getPage(){
        IPage<GetPakge> page =  new Page<>();
        page.setSize(1);
        page.setTotal(10);
        QueryWrapper<GetPakge> wrapper = new QueryWrapper<>();
        getPakge.selectPage(page,wrapper);
    }
}
